import { login, logout, getInfo,getly } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
/* Layout */
import Layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [] // 新增
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 新增
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  END_NUM:(state, end_num) =>{
    state.end_num = end_num
  },
  END_TIME:(state, end_time) =>{
    state.end_time = end_time
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {

      login({ username: username.trim(), password: password }).then(response => {
        // const { data } = response
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })

    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        // 接口返回的roles一定要是一个list，类似['admin','teacher']这种，没有的话自己处理一下也可以
        const { roles, admin_name, admin_head, introduction,end_num, end_time} = data
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('END_NUM', end_num)
        commit('END_TIME', end_time)
        commit('SET_ROLES', roles)
        commit('SET_NAME', admin_name)
        commit('SET_AVATAR', admin_head)
        //commit('SET_INTRODUCTION', introduction)//个人简介
        resolve(data)

      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        // 退出登陆的时候清空一下子
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // 重置token的时候也清空一下子
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 改变角色 这个这个方法登录的时候不用 登录成功后切换角色后使用，后续如果需要切换角色的话，这个可以试试
  changeRoles({ commit, dispatch }, roles) {
    return new Promise(async resolve => {
      //  跟换token
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo') // 调用文件里的getInfo方法
      resetRouter()

      // 根据角色生成可访问的路由图
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // 动态添加可访问路由
      router.addRoutes(accessRoutes)

      // 重置已访问视图和缓存视图
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  //返回
  getly({ commit, state }) {
  return new Promise((resolve, reject) => {
    getly(state.token).then(response => {
      const { data } = response
      //let arr_data = Array.from(data)
      // let arr_data = JSON.parse( JSON.stringify( data ) )
      // let arr_data = Array.prototype.slice.call(data)
      let arr_data = Object.values(data)
      console.log('arr_data1',arr_data)
      arr_data.map(i=>{
        i.component = Layout
        i.meta = {
          title:i.name,
          icon:i.icon,
        },
        i.children.map(j => {
          j.meta = {
            title: j.name
          }
        })
      })

      resolve(data)

    }).catch(error => {
      reject(error)
    })
  })
},


}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


